package com.yunxin.admin.system.application.impl;

import cn.hutool.core.text.CharSequenceUtil;
import com.yunxin.admin.system.application.DeptApplicationService;
import com.yunxin.admin.system.application.assembler.DeptAssembler;
import com.yunxin.admin.system.application.command.AddDeptCommand;
import com.yunxin.admin.system.application.command.UpdateDeptCommand;
import com.yunxin.admin.system.domain.model.dept.Dept;
import com.yunxin.admin.system.domain.model.dept.DeptRepository;
import com.yunxin.admin.system.infra.common.constant.SystemConstants;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

/**
 * 部门业务实现类
 *
 * @author zero°
 * @since 2023-05-22
 */
@Service
@RequiredArgsConstructor
public class DeptApplicationServiceImpl implements DeptApplicationService {

    private final DeptRepository deptRepository;

    private final DeptAssembler deptAssembler;

    @Override
    public Long saveDept(AddDeptCommand command) {
        Dept entity = deptAssembler.formAddDeptCommand(command);
        // 部门路径
        String treePath = generateDeptTreePath(entity.getParentId());
        entity.setTreePath(treePath);
        // 保存部门并返回部门ID
        entity.setBoke(1);
        deptRepository.saveDept(entity);
        return entity.getId();
    }

    @Override
    public Long updateDept(UpdateDeptCommand command) {
        Dept entity = deptAssembler.formUpdateDeptCommand(command);
        // 部门路径
        String treePath = generateDeptTreePath(entity.getParentId());
        entity.setTreePath(treePath);
        // 保存部门并返回部门ID
        deptRepository.updateDept(entity);
        return entity.getId();
    }


    @Override
    public boolean deleteByIds(String ids) {
        // 删除部门及子部门
        if (CharSequenceUtil.isNotBlank(ids)) {
            String[] menuIds = ids.split(",");
            for (String deptId : menuIds) {
                deptRepository.remove(Long.parseLong(deptId));
            }
        }
        return true;
    }

    /**
     * 部门路径生成
     *
     * @param parentId parentId
     * @return String
     */
    private String generateDeptTreePath(Long parentId) {
        String treePath = null;
        if (SystemConstants.ROOT_NODE_ID.equals(parentId)) {
            treePath = String.valueOf(parentId);
        } else {
            Dept parent = deptRepository.getDeptById(parentId);
            if (parent != null) {
                treePath = parent.getTreePath() + "," + parent.getId();
            }
        }
        return treePath;
    }


}
